<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Articles;
use think\exception\ValidateException;
use think\Request;

class Article extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $condition = $this->request->post('condition');
        $data = Articles::where($condition)->paginate(30);
        return $this->success('获取成功', $data);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $this->checkLogin();
        if (!$this->auth->check('create_article', $this->user->id)) return $this->error('权限不足');
        try {
            $this->validate($request->post(), \app\validate\Article::class);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
        $data = $request->post();
        $data['user_id'] = $this->user->id;
        $data['status'] = 1;
        if (Articles::create($data)) {
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
        $data = Articles::with(['user'])->find($id);
        return $this->success('获取成功', $data);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
        if (!$this->auth->check('update_article', $id)) return $this->error('权限不足');
        try {
            $this->validate($request->post(), \app\validate\Article::class);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
        if (Articles::update($request->post(), ['id' => $id])) {
            return $this->success('修改成功');
        } else {
            return $this->error('修改失败');
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        if (!$this->auth->check('delete_article', $id)) return $this->error('权限不足');
        if (Articles::destroy($id)) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
}
